package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.service.ICodeServiceFeignClient;
import com.lagou.edu.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author stevejson
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Resource
    private TokenDao tokenDao;

    @Resource
    private ICodeServiceFeignClient codeServiceFeignClient;

    @Override
    public boolean register(HttpServletResponse response, String email, String password, String code) {
        Token token = tokenDao.findFirstByEmail(email);
        if(null != token){
            return false;
        }
        Integer integer = codeServiceFeignClient.validateCode(email, code);
        if(integer != 0){
            return false;
        }
        //生成token，随机uuid
        String tokens= UUID.randomUUID().toString();
        token= new Token();
        token.setEmail(email);
        token.setToken(tokens);
        try {
            tokenDao.save(token);
        } catch (Exception e) {
            log.error("token存储数据库出错", e);
            return false;
        }
        IUserService.addCookie(response, TOKEN, tokens);
        return true;
    }

    @Override
    public boolean isRegistered(String email) {
        Token token = tokenDao.findFirstByEmail(email);
        return token != null;

    }

    @Override
    public String login(HttpServletResponse response, String email, String password) {
        Token token = tokenDao.findFirstByEmail(email);
        if(null == token){
            return "";
        }
        //生成token，随机uuid
        String tokens= UUID.randomUUID().toString();
        token.setToken(tokens);
        try {
            tokenDao.save(token);
        }catch (Exception e){
            log.error("token更新失败", e);
            return "";
        }
        IUserService.addCookie(response, TOKEN, tokens);
        return email;
    }

    @Override
    public String info(String token) {
        Token tokenObject = tokenDao.findFirstByToken(token);
        if(null == tokenObject){
            return "";
        }
        return tokenObject.getEmail();
    }


}
